package com.yql.biz.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yql.biz.core.config.FactoryConfig;
import com.yql.base.utils.ResultUtil;
import com.yql.common.annotation.PassLogin;
import com.yql.commonextend.response.CommonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@CrossOrigin
@RestController
@RequestMapping("/app/common")
public class ApiController {

    @Autowired
    FactoryConfig factoryConfig;

    @PostMapping("/api")
    @PassLogin
    public JSONObject commonApi(@RequestBody String requestJson){
        JSONObject Resp = new JSONObject();
        JSONObject params = JSONUtil.parseObj(requestJson);
        JSONObject Head = params.getJSONObject("Head");
        String OrgNo = Head.getStr("OrgNo");//固定
        String TxCode = Head.getStr("TxCode");//固定
        String ApiCode = Head.getStr("ApiCode");
        JSONObject Req = params.getJSONObject("Req");
        JSONObject data = Req.getJSONObject("data");

        JSONObject result = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = simpleDateFormat.format(new Date());
        Resp.set("TxTime", nowTime);
        Resp.set("TxCode", TxCode);
        if ("".equals(TxCode) || null == TxCode) {
            Resp.set("RetCode", "E9999");
            Resp.set("RetMsg", "交易码错误");
            result = ResultUtil.buildResult(OrgNo, TxCode, ApiCode, Resp);
            return result;
        }

        CommonResponse commonResponse = factoryConfig.methodFactory(ApiCode, data.toString());
        Resp.set("RetCode", commonResponse.getCode());
        Resp.set("RetMsg", commonResponse.getMsg());
        Resp.set("RetData", commonResponse.getData());
        result = ResultUtil.buildResult(OrgNo, TxCode, ApiCode, Resp);
        return result;
    }
}
